<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    代理模式 |  Yolin
  </title>
  <meta name="generator" content="hexo-theme-yilia-plus">
  
  <link rel="shortcut icon" href="/favicon.png" />
  
  
<link rel="stylesheet" href="/css/style.css">

  
<script src="/js/pace.min.js"></script>


  

  

<link rel="alternate" href="/atom.xml" title="Yolin" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    <main class="content">
      <section class="outer">
  <article id="post-代理模式" class="article article-type-post" itemscope
  itemprop="blogPost" data-scroll-reveal>

  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  代理模式
</h1>
  

    </header>
    

    
    <div class="article-meta">
      <a href="/2020/10/29/%E4%BB%A3%E7%90%86%E6%A8%A1%E5%BC%8F/" class="article-date">
  <time datetime="2020-10-29T07:45:02.000Z" itemprop="datePublished">2020-10-29</time>
</a>
      
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a>
  </div>

      
      
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">961字</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">3分钟</span>
        </span>
    </span>
</div>

      
    </div>
    

    
    
    <div class="tocbot"></div>





    

    <div class="article-entry" itemprop="articleBody">
      


      

      
      <h2 id="1-何为代理模式"><a href="#1-何为代理模式" class="headerlink" title="1.何为代理模式"></a>1.何为代理模式</h2><p><strong>目的</strong>：为其他对象提供一种代理以控制这个对象的访问</p>
<p><strong>何时使用</strong>：想在访问一个类时做一些控制</p>
<p><strong>解决方案</strong>：增加中间层</p>
<p><strong>优点</strong>：高扩展性、清晰</p>
<p><strong>缺点</strong>：实现代理模式需要额外的工作，可能会造成请求的处理速度变慢</p>
<pre><code>SpringAOP的底层就是代理模式</code></pre><p><strong>代理模式的分类</strong>：</p>
<blockquote>
<p>  <strong>静态代理</strong><br>  <strong>动态代理</strong></p>
</blockquote>
<h2 id="2-静态代理"><a href="#2-静态代理" class="headerlink" title="2.静态代理"></a>2.静态代理</h2><p>举一个生活中租房子的例子</p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-10-25_13-08-48.jpg" alt=""></p>
<a id="more"></a>

<h4 id="角色分析："><a href="#角色分析：" class="headerlink" title="角色分析："></a>角色分析：</h4><ul>
<li>抽象角色：一般会使用接口或抽象类来解决（租房）</li>
<li>真实角色：被代理的角色（房东）</li>
<li>代理角色：代理真实角色，代理真实角色后，我们一般会做一些附属操作（中介）</li>
<li>客户：访问代理对象的人（租房的人）</li>
</ul>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-10-25_14-18-59.jpg" alt=""></p>
<p><strong>再来加深一下理解</strong></p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-10-25_15-26-59.jpg" alt=""></p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-10-25_15-55-25.jpg" alt=""></p>
<h4 id="代理模式的好处"><a href="#代理模式的好处" class="headerlink" title="代理模式的好处"></a>代理模式的好处</h4><pre><code>&gt;    可以使真实角色的操作更加纯粹！不用去关注一些公共的业务（房东只想着租房子，不想打广告啦，签合同之类）
&gt;    公共业务发生扩展的时候方便集中管理
&gt;    降低耦合</code></pre><h4 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h4><pre><code>&gt;    一个真实角色就会产生一个代理角色；代码量会翻倍~开发效率会变低</code></pre><p>为解决这一问题需要用到动态代理~</p>
<h2 id="3-动态代理"><a href="#3-动态代理" class="headerlink" title="3. 动态代理"></a>3. 动态代理</h2><p><strong>特点</strong>：字节码随用随创建，随用随加载</p>
<p><strong>作用</strong>：不修改源码的基础上对方法增强</p>
<ul>
<li>动态代理和静态代理角色一样</li>
<li>动态代理的代理类是动态生成的，不是直接写好的</li>
<li>动态代理分为两大类<blockquote>
<p>  基于接口的动态代理（JDK动态代理）<br>  基于类的动态代理（cglib）</p>
</blockquote>
</li>
</ul>
<p>需要了解的两个类：Proxy（代理），InvocationHandler（调用处理程序）</p>
<h3 id="InvocationHandler官方文档"><a href="#InvocationHandler官方文档" class="headerlink" title="InvocationHandler官方文档"></a>InvocationHandler官方文档</h3><p>InvocationHandler是由代理实例的调用处理程序实现的接口。<br>每个代理实例都有一个关联的调用处理程序。当在代理实力上调用方法时，方法调用将被编码并分派到其调用处理程序的invoke方法。</p>
<table>
<thead>
<tr>
<th>返回值</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>Object</td>
<td>invoke（Object proxy,方法 method，Object[] args）处理代理实例上的方法调用并返回结果</td>
</tr>
</tbody></table>
<h3 id="如何创建代理对象？"><a href="#如何创建代理对象？" class="headerlink" title="如何创建代理对象？"></a>如何创建代理对象？</h3><blockquote>
<p>  <strong>使用Proxy类中的newProxyInstance方法</strong></p>
</blockquote>
<h3 id="创建代理的要求："><a href="#创建代理的要求：" class="headerlink" title="创建代理的要求："></a>创建代理的要求：</h3><blockquote>
<p>  <strong>被代理类最少实现一个接口，如果没有则不能使用</strong></p>
</blockquote>
<h3 id="newProxyInstance-方法的三个参数："><a href="#newProxyInstance-方法的三个参数：" class="headerlink" title="newProxyInstance()方法的三个参数："></a><strong>newProxyInstance()方法的三个参数</strong>：</h3><blockquote>
<p>  ClassLoader:类加载器</p>
<ul>
<li><p>用于加载代理对象字节码的，和被代理对象使用相同的类加载器。固定写法</p>
<p>Class[]:字节码数组</p>
</li>
<li><p>用于让代理对象和被代理对象有相同的方法。固定写法</p>
<p>InvocationHandler:用于提供增强的代码</p>
</li>
<li><p>让我们写如何代理，一般都是该接口的实现类，谁用写谁</p>
</li>
</ul>
</blockquote>
<h3 id="使用动态代理来实现租房案例"><a href="#使用动态代理来实现租房案例" class="headerlink" title="使用动态代理来实现租房案例"></a>使用动态代理来实现租房案例</h3><p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-10-29_10-38-36.jpg" alt=""></p>
<h3 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> xyz.demo2;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Client</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> &lt;R&gt; <span class="function"><span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//真实角色</span></span><br><span class="line">        Host host = <span class="keyword">new</span> Host();</span><br><span class="line">        <span class="comment">//代理角色</span></span><br><span class="line">        ProxyInvocationHandler pih = <span class="keyword">new</span> ProxyInvocationHandler();</span><br><span class="line">        <span class="comment">//通过调用程序处理角色来处理我们要调用的接口对象</span></span><br><span class="line">        pih.setRent(host);</span><br><span class="line">        rent proxy = (rent) pih.getProxy();</span><br><span class="line">        proxy.rent();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//房东要出租房子</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h3><pre><code>getProxy方法返回代理对象，这个代理对象是代理类的一个实例，代理类也实现了Rent接口重写了rent方法，所以代理对象proxy调用rent方法就会在代理类的rent方法中调用invoke方法</code></pre><h3 id="加深理解"><a href="#加深理解" class="headerlink" title="加深理解"></a>加深理解</h3><p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-10-29_14-07-00.jpg" alt=""></p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-10-29_13-56-34.jpg" alt=""></p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p><strong>动态代理主要是通过反射机制，在运行时动态生成所需代理的class。我们可以直接去使用动态代理类，但必须要了解的是Proxy和InvocationHandler，Proxy是生成动态代理实例的，InvocationHandler是调用程序并返回结果的</strong></p>

      
      <!-- reward -->
      
    </div>
      <!-- copyright -->
      
    <footer class="article-footer">
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86/" rel="tag">动态代理</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E9%9D%99%E6%80%81%E4%BB%A3%E7%90%86/" rel="tag">静态代理</a></li></ul>


    </footer>

  </div>

  
  
  <nav class="article-nav">
    
      <a href="/2020/11/01/%E9%9D%A2%E5%90%91%E5%88%87%E9%9D%A2%E7%BC%96%E7%A8%8BAOP/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            面向切面编程AOP
          
        </div>
      </a>
    
    
      <a href="/2020/10/24/Spring%E6%A1%86%E6%9E%B6%E7%9A%84%E4%BD%BF%E7%94%A8%EF%BC%88%E4%BA%8C%EF%BC%89/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Spring框架的使用（二）</div>
      </a>
    
  </nav>


  

  
  
<!-- valine评论 -->
<div id="vcomments-box">
    <div id="vcomments">
    </div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/valine@1.3.10/dist/Valine.min.js'></script>
<script>
    new Valine({
        el: '#vcomments',
        notify: false,
        verify: '',
        app_id: '',
        app_key: '',
        path: window.location.pathname,
        avatar: 'mp',
        placeholder: '给我的文章加点评论吧~',
        recordIP: true
    });
    const infoEle = document.querySelector('#vcomments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
        infoEle.childNodes.forEach(function (item) {
            item.parentNode.removeChild(item);
        });
    }
</script>
<style>
    #vcomments-box {
        padding: 5px 30px;
    }

    @media screen and (max-width: 800px) {
        #vcomments-box {
            padding: 5px 0px;
        }
    }

    #vcomments-box #vcomments {
        background-color: #fff;
    }

    .v .vlist .vcard .vh {
        padding-right: 20px;
    }

    .v .vlist .vcard {
        padding-left: 10px;
    }
</style>

  

  
  
  

</article>
</section>
      <footer class="footer">
  <div class="outer">
    <ul class="list-inline">
      <li>
        &copy;
        2020-2021
        张金
      </li>
      <li>
        
      </li>
    </ul>
    <ul class="list-inline">
      <li>
        
        
        <span>
  <i>PV:<span id="busuanzi_value_page_pv"></span></i>
  <i>UV:<span id="busuanzi_value_site_uv"></span></i>
</span>
        
      </li>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
        <img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/beian.png">
        <a href="https://beian.miit.gov.cn"  style="color:#f72b07" target="_blank">陕ICP备20002449号</a>
      </li>

    </ul>
  </div>
</footer>
    <div class="to_top">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>
      </div>
    </main>
      <aside class="sidebar">
        <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Yolin"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/playlist">歌单</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/video">视频</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友情链接</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
      </aside>
      <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
      
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/jquery.justifiedGallery.min.js"></script>


<script src="/js/lazyload.min.js"></script>


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<script src="/js/share.js"></script>




<script>
  try {
    var typed = new Typed("#subtitle", {
    strings: ['肠断月明红豆蔻,','月似当时,','人似当时否？'],
    startDelay: 1500,
    typeSpeed: 200,
    loop: true,
    backSpeed: 40,
    showCursor: true
    });
  } catch (err) {
  }
  
</script>




<script src="/js/tocbot.min.js"></script>

<script>
  // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer:'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
    onClick: (e) => {
      $('.toc-link').removeClass('is-active-link');
      $(`a[href=${e.target.hash}]`).addClass('is-active-link');
      $(e.target.hash).scrollIntoView();
      return false;
    }
  });
</script>


<script>
  var ayerConfig = {
    mathjax: true
  }
</script>


<script src="/js/ayer.js"></script>


<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>



<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>


<script type="text/javascript" src="https://js.users.51.la/20544303.js"></script>
  </div>
</body>

</html>